<template>
	<view @click="selectAndUpload()">
		<slot></slot>
	</view>
</template>

<script>
	import {
		HTTP_REQUEST_URL,
		HEADER,
		TOKENNAME,
		HEADERPARAMS
	} from '@/config/app';
	export default {
		name: "image-upload",
		data() {
			return {
				uploadHeaders: {
					"accessToken": uni.getStorageSync('loginInfo').accessToken
				}
			}
		},
		props: {
			maxCount:{
				type: Number,
				default: 1
			},
			maxSize: {
				type: Number,
				default: 5*1024*1024
			},
			sourceType:{
				type: String,
				default: 'album'
			},
			onBefore: {
				type: Function,
				default: null
			},
			onSuccess: {
				type: Function,
				default: null
			},
			onError: {
				type: Function,
				default: null
			}
		},
		mounted() {
		
		},
		methods: {
			selectAndUpload() {
				uni.chooseImage({
					count: this.maxCount, //最多可以选择的图片张数，默认9
					sourceType: [this.sourceType], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					sizeType: ['original'], //original 原图，compressed 压缩图，默认二者都有
					success: (res) => {
						res.tempFiles.forEach((file) => {
							// 校验大小
							if (this.maxSize && file.size > this.maxSize) {
								this.$u.taost(`文件大小不能超过 ${this.fileSizeStr}!`);
								this.$emit("fail", file);
								return;
							}
							
							// if (!this.onBefore || this.onBefore(file)) {
							// 	// 调用上传图片的接口
								
							// }
							this.$emit('onBefore',file,(data) => {
								// 在这里处理从父组件返回的数据  
								if(data){
									this.uploadImage(file);
								}
							  })
							// if(this.$emit('onBefore',file)){
								
							// }
							// this.uploadImage(file);
						})
					},
					fail(err) {
						console.log("err",err)
					}
				})
			},
			uploadImage(file) {
				let  header = HEADER
	            if (this.$store.state.app.token) header[TOKENNAME] = this.$store.state.app.token;
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/file/upload',
					header: header,
					filePath: file.path, // 要上传文件资源的路径
					name: 'file',
					success: (res) => {
						console.log(111,res)
						let data = JSON.parse(res.data);
							console.log(222,data)
						if(data.code != 0){
							// this.onError && this.onError(file, data);
							this.$emit('onError',file, data)
						}else{
							console.log('onSuccess')
							this.$emit('onSuccess',file, data)
							// this.onSuccess && this.onSuccess(file, data);
						}
					},
					fail: (err) => {
						console.log(err);
						// this.onError && this.onError(file, err);
						this.$emit('onError',file, data)
					}
				})
			}
		},
		computed: {
			fileSizeStr() {
				if (this.maxSize > 1024 * 1024) {
					return Math.round(this.maxSize / 1024 / 1024) + "M";
				}
				if (this.maxSize > 1024) {
					return Math.round(this.maxSize / 1024) + "KB";
				}
				return this.maxSize + "B";
			}
		}
	}
</script>

<style>
</style>